package com.cn.wanxi.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter("/*")
public class MyFileter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String path = req.getServletPath();
        System.out.println(path);
        HttpSession session = req.getSession();
        Object username = session.getAttribute("username");
        if (path.startsWith("/html/back") || path.startsWith("/back/")) {
            if (username != null) {
                filterChain.doFilter(req, resp);//放行
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result", -1);
                resp.getWriter().println(jsonObject);
            }
        } else {
            filterChain.doFilter(req, resp);//放行
        }


    }

    @Override
    public void destroy() {

    }
}
